<template>
  <div class="mod-config">
    <el-form v-if="loginUser.role == 1 || loginUser.role == 2"  :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item >
        <el-input style="width: 150px;margin-left: 20px" v-model="dataForm.name" placeholder="姓名" clearable></el-input>
      </el-form-item>
      <el-select style="width: 150px;margin-left: 20px" v-model="dataForm.type" clearable placeholder="请选择类型">
        <el-option v-for="item in vipType" :key="item.key" :label="item.value" :value="item.key">
        </el-option>
      </el-select>
      <el-select style="width: 150px;margin-left: 20px" v-model="dataForm.gender" clearable placeholder="请选择性别">
        <el-option v-for="item in genderType" :key="item.key" :label="item.value" :value="item.key">
        </el-option>
      </el-select>
      <el-form-item>
        <el-input style="width: 150px;margin-left: 20px;margin-right: 20px" v-model="dataForm.origin" placeholder="居住地址"
          clearable></el-input>
      </el-form-item>
      <el-form-item v-if="loginUser.role == 1 || loginUser.role == 2" >
          <el-button @click="getDataList()">查询</el-button>
          <el-button style="margin-left: 20px" type="primary" @click="addOrUpdateHandle()">新建</el-button>
          <el-button type="primary" @click="resetPassword()">为用户重置密码</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
      <el-table-column prop="name" header-align="center" align="center" label="姓名">
      </el-table-column>
      <el-table-column prop="identityId" header-align="center" style="width: 210px;" align="center" label="身份证号码">
      </el-table-column>
      <el-table-column prop="gender" header-align="center" align="center" label="性别">
        <template v-slot:default="scope">
          {{ scope.row.gender === 0 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="birthTime" header-align="center" align="center" label="出生日期">
      </el-table-column>
      <el-table-column prop="age" header-align="center" align="center" label="年龄">
      </el-table-column>
      <el-table-column prop="category" header-align="center" align="center" label="类别">
        <template v-slot:default="scope">
          {{ categoryFormat(scope.row.category) }}
        </template>
      </el-table-column>
      <el-table-column prop="origin" header-align="center" align="center" label="籍贯">
      </el-table-column>
      <el-table-column prop="tel" header-align="center" align="center" label="电话">
      </el-table-column>
      <el-table-column prop="address" header-align="center" align="center" label="居住地址">
      </el-table-column>
      <el-table-column prop="recipientNum" header-align="center" align="center" label="对接受助者数量">
      </el-table-column>
      <el-table-column prop="role" header-align="center" align="center" label="用户角色">
        <template v-slot:default="scope">
          {{ roleFormat(scope.row.role) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="300px" label="操作">
        <template v-slot:default="scope">
          <el-button type="primary" size="small" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
          <el-button v-if="loginUser.role == 1 && loginUser.id != scope.row.id" type="primary" size="small"
            @click="setRoleHandle(scope.row.id, scope.row.role, scope.row.name)">设置角色</el-button>

          <el-button
            v-if="(loginUser.role == 1 && loginUser.id != scope.row.id) || (loginUser.role == 2 && loginUser.id != scope.row.id)"
            type="primary" size="small" @click="deleteHandle(scope.row.id, scope.row.recipientNum)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 设置角色弹窗 -->
    <el-dialog title="设置用户角色" :close-on-click-modal="false" :visible.sync="visible" width="45%">
      <el-form :model="setRoleForm" @keyup.enter.native="setRoleFormSubmit()" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="setRoleForm.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色设置" prop="role">
          <el-select style="width: 180px;" v-model="setRoleForm.role" clearable placeholder="角色类型">
            <el-option v-for="item in roleMap" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="setRoleFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog title="重置密码" :close-on-click-modal="false" :visible.sync="resetPasswordVisible" width="45%">
      <el-form :model="setRoleForm" @keyup.enter.native="handleResetPassword()" label-width="80px">
        <el-form-item label="姓名" prop="id">
          <el-select style="width: 500px;" v-model="resetPasswordForm.id" filterable clearable placeholder="请选择姓名（可输入）">
            <el-option v-for="item in fellows" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input style="width: 500px;" v-model="resetPasswordForm.password" clearable type="password"
            placeholder="请输入重置密码">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import AddOrUpdate from './fellow-add-or-update.vue'
import service from "@/utils/httpRequest";
import { Message } from 'element-ui';
import request from "@/utils/httpRequest";

export default {
  data() {
    return {
      resetPasswordForm: {
        id: '',
        password: ""
      },
      resetPasswordVisible: false,
      fellows: [
        {
          id: 0,
          name: '',
          tel: ''
        }
      ],
      genderType: [
        {
          key: 0,
          value: '男'
        },
        {
          key: 1,
          value: '女'
        }
      ],
      vipType: [
        {
          key: 0,
          value: '会员'
        },
        {
          key: 1,
          value: '非会员'
        }
      ],
      roleMap: [
        {
          key: 2,
          value: '普通管理员'
        },
        {
          key: 3,
          value: '普通用户'
        },
        {
          key: 4,
          value: '禁用'
        }
      ],
      dataForm: {
        name: '',
        gender: '',
        type: '',
        origin: ''
      },

      setRoleForm: {
        id: '',
        name: '',
        role: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      visible: false,
      role: ''
    }
  },
  components: {
    AddOrUpdate
  },
  computed: {
    loginUser() {
      return this.$store.state.user?.loginUser || {}  // 使用可选链和默认值 ,
    },
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    roleFormat(roleCode) {
      const roleMap = {
        1: '超级管理员',
        2: '管理员',
        3: '普通用户',
        4: '禁用'
      }
      return roleMap[roleCode] || '未知角色' // 防御性处理 
    },

    categoryFormat(categoryId) {
      const vipType = {
        0: '会员',
        1: '非会员',
        2: '大学生',
      }
      return vipType[categoryId] || '未知角色' // 防御性处理 
    },
    // 获取所有会员
    getFellows() {
      request.get('/lovehelp/fellow/allFellowInfo').then((response) => {
        if (response && response.code === 200) {
          this.fellows = response.fellowVoInfo
        } else {
          this.fellows = []
        }
      }).catch((error) => {
        console.error(error)
      })
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      service({
        method: 'GET',
        url: '/lovehelp/fellow/list',
        params: {
          'page': this.pageIndex,
          'limit': this.pageSize,
          'name': this.dataForm.name,
          'gender': this.dataForm.gender,
          'type': this.dataForm.type,
          'origin': this.dataForm.origin,
        }
      }).then(res => {
        if (res.code === 200) {
          this.dataList = res.page.list
          console.log("会员数据", this.dataList)
          this.totalPage = res.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    handleResetPassword() {
      this.resetPasswordVisible = false
      service({
        method: 'POST',
        url: `/lovehelp/fellow/resetPassword`,
        data: this.resetPasswordForm
      }).then(res => {
        Message.success("密码重置成功")
        this.getDataList()
      })
    },
    //重置密码弹窗逻辑处理
    resetPassword() {
      this.resetPasswordVisible = true

      // 清空表单
      this.resetPasswordForm.password = ""
      //加载会员数据
      this.getFellows()
    },

    setRoleFormSubmit() {
      this.visible = false
      service({
        method: 'POST',
        url: `/lovehelp/fellow/setRole/${this.setRoleForm.id}/${this.setRoleForm.role}`,
      }).then(res => {
        Message.success(res.msg)
        this.getDataList()
      })


    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      console.log("当前修改用户id", id)
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    setRoleHandle(id, role, name) {
      this.visible = true
      this.setRoleForm.id = id
      this.setRoleForm.name = name
      this.setRoleForm.role = role
    },
    // 删除
    deleteHandle(id, num) {
      if (num > 0) {
        this.$message.warning({
          message: "该人员有对接受助者，无法删除",
          type: 'error',
          duration: 5000,

        });
        return
      }
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`此次删除将一起删除该人员的活动记录，确定对其进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service({
          method: 'POST',
          url: '/lovehelp/fellow/delete',
          data: ids
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        this.$message.info("已取消删除");
      })
    }
  }
}
</script>
